import Mock from 'mockjs';
import type { MockRequestOptions } from '../types/mock';

interface ShopItem {
  id: number;
  name: string;
  ingredients: string;
  price: number;
  effect: string;
  createdAt: string;
  image: string;
}

export const mockShopList = Mock.mock({
  'list|1000': [
    {
      'id|+1': 10000,
      'name': '@ctitle(3, 6)',
      'ingredients': '@cparagraph(1, 2)',
      'price|1-999.2': 1,
      'effect': '@cparagraph(3, 5)',
      'createdAt': '@datetime',
      'image': '@image("200x200", "#50B347", "#FFF", "Mock")'
    } as unknown as ShopItem,
  ],
});

export default [
  {
    url: '/api/shoplist',
    method: 'get',
    response: () => ({
      code: 200,
      message: 'success',
      data: mockShopList.list,
    }),
  },
  {
    url: '/api/shoplist/:id',
    method: 'get',
    response: (options: MockRequestOptions) => {
      const id = parseInt(options.url.split('/').pop() || '10000', 10);
      return {
        code: 200,
        message: 'success',
        data: mockShopList.list.find((item: ShopItem) => item.id === id),
      };
    },
  },
  {
    url: /\/api\/shoplist\/\d+$/,
    method: 'delete',
    response: (options: MockRequestOptions) => {
      const id = parseInt(options.url.split('/').pop() || '10000', 10);
      const index = mockShopList.list.findIndex((item: ShopItem) => item.id === id);
      if (index !== -1) {
        mockShopList.list.splice(index, 1);
        return { code: 200, message: '删除成功' };
      }
      return { code: 404, message: '未找到该商品' };
    },
  },
  {
    url: '/api/shoplist',
    method: 'post',
    response: (options: MockRequestOptions) => {
      const newItem = JSON.parse(options.body || '{}');
      const lastId = Math.max(...mockShopList.list.map((item: ShopItem) => item.id), 10000);
      const item: ShopItem = {
        id: lastId + 1,
        name: newItem.name,
        ingredients: newItem.ingredients,
        price: newItem.price,
        effect: newItem.effect,
        createdAt: new Date().toISOString(),
        image: newItem.image || '@image("200x200", "#50B347", "#FFF", "Mock")'
      };
      mockShopList.list.push(item);
      return {
        code: 200,
        message: '添加成功',
        data: item
      };
    },
  },
];